package com.translate.web.service.impl;

import com.common.util.CopyEntity;
import com.translate.web.constant.RedisConstant;
import com.translate.web.dao.ProductMapper;
import com.translate.entity.Product;
import com.translate.web.service.IProductService;
import com.basic.service.impl.BaseServiceImpl;
import com.translate.vo.contract.IProductVO;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * 商品服务
 * @author 111
 */
@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {
	
	private RedisTemplate<String, List<Product>> redisTemplate;
	
	@Resource
	public void setRedisTemplate(RedisTemplate<String, List<Product>> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	public ProductServiceImpl(ProductMapper mapper) {
		super(mapper);
	}

	protected void insertPropteris(Product data) {
		long time = System.currentTimeMillis() / 1000;
		data.setCreateTime(time);
		
		data.setStatus(1);
		data.setUpdateTime(time);
	}

	protected void updatePropteris(Product data) {
		data.setUpdateTime(System.currentTimeMillis() / 1000);
	}

	@Override
	protected int getId(Product data) {
		return data.getId();
	}

	protected Class<Product> getEntityClass() {
		return Product.class;
	}

	@Override
	public List<Product> getProductsListToCache(Integer[] ids) {
		
		String key = RedisConstant.getProductListKey(ids);
		
		ValueOperations<String, List<Product>> valueOperations = this.redisTemplate.opsForValue();
		
		List<Product> products = valueOperations.get(key);
		
		if (null != products) {
			return products;
		}
		
		products = this.getDataByIds(ids);
		
		
		if (null == products) {
			products = new ArrayList<>(0);
			
			valueOperations.set(key, products, 3, TimeUnit.SECONDS);
			
			return products;
		}
		
		valueOperations.set(key, products, 9, TimeUnit.SECONDS);
		
		return products;
	}

	
	
	
	@Override
	public Map<Integer, BigDecimal> getProductsListToCacheCovertMap(Integer[] ids) {
		Map<Integer, BigDecimal> map = new HashMap<>();

		List<Product> products = this.getProductsListToCache(ids);
		
		for (Product product : products) {
			map.put(product.getId(), product.getPrice());
		}
		
		return map;
	}

	@Override
	public <VO extends IProductVO> List<VO> getVOsToCache(Integer[] ids, Class<VO> target) {
		
		List<Product> products = this.getProductsListToCache(ids);
		
		List<VO> vos = new ArrayList<>(ids.length *4 /3);
		
		VO obj;
		
		
		for (Product product : products) {
			
			obj = CopyEntity.copyEntity(product, target);
			
			vos.add(obj);
		}
		
		return vos;
	}
}